import {WebSocket} from "ws";
import {getCredentials} from "@/main/lcu/LcuCertificate.js";
import {logger} from "@/main/log.js";
import {BrowserWindow} from "electron";


const createWebSocket = () => {
    const {token, port} = getCredentials();
    const ws = new WebSocket(`wss://127.0.0.1:${port}`, {
        headers: {
            Authorization: token,
            'Content-Encoding': 'UTF-8'
        },
        protocol: 'wamp',
        rejectUnauthorized: false,
    })
    return ws;
}


function initEventHandlerManager() {
    const eventMap = new Map();

    //英雄选择阶段会话信息同步
    eventMap.set("/lol-gameflow/v1/session", ({data, eventType}) => {
        sendMessageToAllWindow('sync/game-flow', {
            data, eventType
        })
    })

    eventMap.set("/lol-champ-select/v1/session", ({data, eventType}) => {
        sendMessageToAllWindow('sync/champion-session', {
            data, eventType
        })
    })

    eventMap.set("/lol-lobby/v2/lobby", ({data, eventType}) => {
        sendMessageToAllWindow('sync/lobby', {
            data, eventType
        })
    })


    return eventMap;
}


/**
 * 目前已知的uri 列表
 *
 *  '/lol-champ-select/v1/summoners/*' 进入房间后  房间召唤师信息
 *  `/lol-champ-select/v1/session` 当前对局消息
 * @param eventStatusCallback
 * @param wsStatusCallback
 * @returns {Promise<unknown>}
 */

const ignoreUri = ['/lol-premade-voice/v1/participant-records', '/lol-premade-voice/v1/participants']

async function startWebSocketService(
    wsStatusCallback, reconnect,gameStatusCallback,
) {
    const evenManager = initEventHandlerManager();

    const ws = createWebSocket();

    ws.on('open', (event) => {
        wsStatusCallback('connect');
        ws.send(JSON.stringify([5, 'OnJsonApiEvent']));
    })

    ws.onerror = (err) => {
        wsStatusCallback('disconnect');
        reconnect();
    }
    ws.onclose = () => {
        wsStatusCallback('disconnect');
        reconnect();
    }

    ws.on('message', (message) => {
        try {
            const [, , basic] = JSON.parse(message)
            const {uri, data, eventType} = basic;
            const {phase} = data;
            //phase 单独同步
            if (phase) {
                sendMessageToAllWindow('sync/phase', {
                    data: phase,
                    eventType: 'Update'
                })
                gameStatusCallback(phase);

            }
            //后续的批量同步
            if (evenManager.get(uri)) {
                evenManager.get(uri)({data, eventType});
            }
            if (false === ignoreUri.includes(uri)) {
                console.log(uri, eventType)
            }

        } catch (err) {
        }
    })
    return {
        "ws": ws
    }
}

function sendMessageToAllWindow(event, args) {
    BrowserWindow.getAllWindows().forEach(win => {
        win.webContents.send(event, args)
    })
}


export {
    startWebSocketService, sendMessageToAllWindow
}








